package com.example.spider.cluster.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.CompositeCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * UI：https://github.com/qishibo/AnotherRedisDesktopManager/releases
 * redis 序列化选择、性能 https://www.shenyanchao.cn/blog/2019/02/13/redis-serializer/
 * import RedissonCacheStatisticsAutoConfiguration
 */
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedissonConfig {

    /**
     * 替代 Jcache 支持分布式
     */
//    @Bean
//    public RedissonSpringCacheManager cacheManager(RedissonClient redissonClient) throws IOException {
//        shoulder-batch-progressCache_DEFAULT
//        Map<String, CacheConfig> config = new HashMap<>();
//        CacheConfig c = new CacheConfig();
//        c.setMaxSize(1000);
//        c.setMaxIdleTime(Duration.ofHours(1).toMillis());
//        config.put("shoulder-batch-progressCache_DEFAULT", c);
//        return new RedissonSpringCacheManager(redissonClient, config);
//    }

    /**
     * 所有对Redisson的使用都是通过RedissonClient对象
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient(RedisProperties redisProperties, ObjectMapper objectMapper) {
        // 创建配置 指定redis地址及节点信息
        Config config = new Config();
        String url = "redis://%s:%s".formatted(redisProperties.getHost(), redisProperties.getPort());
        config.useSingleServer().setAddress(url).setPassword(redisProperties.getPassword());
        // 默认序列化 LZ4(Kyp)。优点：带宽/内存占用下降，响应更快；缺点：可视化工具不可读；
        config.setCodec(new CompositeCodec(StringCodec.INSTANCE, new JsonJacksonCodec(objectMapper), new JsonJacksonCodec(objectMapper)));
        // 根据config创建出RedissonClient实例
        return Redisson.create(config);
    }

    @Bean
    public RedisBatchProgressCache redisBatchProgressCache(RedissonClient redissonClient,
                                                           @Value("${spider.progress.cachePrefix}") String progressCachePrefix,
                                                           @Value("${spider.progress.cacheAtrrPrefix}") String progressAtrrPrefix) {
        RedisFixedNumProgress.setCacheKeyPrefix(progressCachePrefix);
        RedisFixedNumProgress.setCacheKeyPrefix(progressCachePrefix);
        return new RedisBatchProgressCache(redissonClient);
    }
}